package com.qf.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.qf.pojo.DtsPermission;
import com.qf.pojo.DtsRole;
import com.qf.service.PermissionService;
import com.qf.service.RoleService;
import com.qf.util.*;
import com.qf.vo.PermVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@CrossOrigin("*")
@RequestMapping("/role")
public class RoleController {
    @Autowired
    private RoleService roleService;

    @Autowired
    private PermissionService permissionService;

    @Autowired
    private ApplicationContext context;

    private List<PermVo> systemPermissions = null;
    private Set<String> systemPermissionsString = null;

    @RequestMapping("/options")
    public Object options(){
        List<DtsRole> roleList = roleService.findAllRoleList();

        List<Map<String,Object>> resultList = new ArrayList<>();
        if (roleList != null){
            for (DtsRole dtsRole : roleList) {
                Map<String,Object> data = new HashMap<>();
                data.put("value",dtsRole.getId());
                data.put("label",dtsRole.getName());
                resultList.add(data);
            }
        }

        return ResponseUtil.ok(resultList);
    }


    /**
     * 分页查询角色列表
     * @param page
     * @param limit
     * @param sort
     * @param order
     * @param rolename
     * @return
     */
    @RequestMapping("/list")
    public Object list(Integer page,Integer limit, String sort,String order,String rolename){
        IPage<DtsRole> iPage = roleService.findByPage(page, limit, sort, order, rolename);

        Map<String,Object> data = new HashMap<>();

        data.put("tatal",iPage.getTotal());
        data.put("items",iPage.getRecords());

        return ResponseUtil.ok(data);
    }

    /**
     * 新增角色
     * @param role
     * @return
     */
    @RequestMapping("/create")
    public Object create(@RequestBody DtsRole role){

        role = roleService.add(role);

        return ResponseUtil.ok(role);
    }

    /**
     * 修改角色
     * @param role
     * @return
     */
    @RequestMapping("/update")
    public Object update(@RequestBody DtsRole role){
        int update = roleService.update(role);
        if (update == 0){
            return ResponseUtil.updatedDataFailed();
        }
        return ResponseUtil.ok(role);
    }


    /**
     * 删除角色
     * @param role
     * @return
     */
    @RequestMapping("/delete")
    public Object delete(@RequestBody DtsRole role){
        Integer id = role.getId();
        if (id == null){
            return ResponseUtil.badArgument();
        }
        roleService.deleteById(id);
        return ResponseUtil.ok();
    }

    /**
     * 获取指定包下所有controller需要的权限对象集合
     * @return
     */
    private List<PermVo> getSystemPermissions(){
        final String basicPackage = "com.qf";
        if (systemPermissions == null){
            List<Permission> permissions = PermissionUtil.listPermission(context, basicPackage);
            systemPermissions = PermissionUtil.listPermVo(permissions);
            systemPermissionsString = PermissionUtil.listPermissionString(permissions);
        }
        return systemPermissions;
    }

    /**
     * 根据角色id, 获取权限字符串集合
     * 例如: admin:category:list或者admin:category:read等
     * @param roleId
     * @return
     */
    private Set<String> getAssignedPermission(Integer roleId){
        // 这里需要注意的是，如果存在超级权限*，那么这里需要转化成当前所有系统权限。
        // 之所以这么做，是因为前端不能识别超级权限，所以这里需要转换一下。
        Set<String> assignedPermission = null;
        if (permissionService.checkSuperPermission(roleId)){
            getSystemPermissions();
            assignedPermission = systemPermissionsString;
        }else {
            assignedPermission = permissionService.findPermByRoleId(roleId);
        }

        return assignedPermission;
    }

    /**
     * 管理员的权限情况
     * @param roleId
     * @return 系统所有权限列表和管理员已分配权限
     */
    @GetMapping ("/permissions")
    public Object permission(Integer roleId){
        List<PermVo> systemPermissions = getSystemPermissions();
        Set<String> assignedPermission = getAssignedPermission(roleId);

        Map<String,Object> data = new HashMap<>();
        data.put("systemPermissions", systemPermissions);
        data.put("assignedPermission",assignedPermission);

        return ResponseUtil.ok(data);
    }

    @PostMapping("/permissions")
    public Object updatePermissions(@RequestBody String body){
        Integer roleId = JacksonUtil.parseInteger(body, "roleId");
        List<String> permissions = JacksonUtil.parseStringList(body, "permissions");
        if (roleId == null || permissions == null){
            return ResponseUtil.badArgument();
        }

        // 如果修改的角色是超级权限，则拒绝修改。
        if (permissionService.checkSuperPermission(roleId)){
            return AdminResponseUtil.fail(AdminResponseCode.ROLE_SUPER_SUPERMISSION);
        }

        // 先删除旧的权限，再更新新的权限
        permissionService.deleteByRoleId(roleId);
        for (String permission : permissions) {
            DtsPermission dtsPermission = new DtsPermission();
            dtsPermission.setRoleId(roleId);
            dtsPermission.setPermission(permission);
            permissionService.add(dtsPermission);
        }

        return ResponseUtil.ok();
    }

}
